package com.x.chalk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.x.chalk.dao.UsefulNewsDao;
import com.x.chalk.dao.UsefulNewsLikesDao;
import com.x.chalk.entity.UsefulNewsLikes;
import com.x.chalk.service.intf.UsefulNewsLikesService;
import com.x.chalk.vo.R;
import org.springframework.stereotype.Service;

@Service
public class UsefulNewsLikesServiceImpl implements UsefulNewsLikesService {

    private final UsefulNewsLikesDao dao;
    private final UsefulNewsDao usefulNewsDao;

    public UsefulNewsLikesServiceImpl(UsefulNewsLikesDao dao, UsefulNewsDao usefulNewsDao) {
        this.dao = dao;
        this.usefulNewsDao = usefulNewsDao;
    }

    /**
     * 点赞*/
    @Override
    public R like(Integer id, String token) {
        Integer uid=Integer.parseInt(token);
        QueryWrapper<UsefulNewsLikes> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("usefulid",id);
        queryWrapper.eq("uid",uid);
        UsefulNewsLikes unl=dao.selectOne(queryWrapper);
        //如果没有点过赞则为null
        if (unl==null){
            //添加点赞记录
            unl=new UsefulNewsLikes(uid,id);
            dao.insert(unl);
            //点赞数加一
            usefulNewsDao.updateLike(id,1);
        }else {
            //点过赞了 本次为取消点赞
            dao.deleteById(unl.getId());
            //文章点赞数减一
            usefulNewsDao.updateLike(id,-1);
        }
        return R.ok();
    }
}
